from flask import Flask, render_template,session,request,flash,redirect,url_for
import os

app = Flask(__name__)
app.secret_key = os.urandom(24)
#临时存储的变量，代替数据库
users={}
@app.route('/')
def index():
    hasLogin =  'username' in session and session['username'] in users
    if hasLogin:
       return render_template('index.html',hasLogin=hasLogin)
    flash('You are logged in', 'success')
    return redirect(url_for('login'))


@app.route('/register', methods=['GET', 'POST'])
def register():
    form_data={}
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        password2 = request.form['password2']
        form_data = {'username':username, 'password':password, 'password2':password2}

        # 检查用户名是否已存在
        if username in users:
            flash('用户名已存在，请更换一个', 'danger')
            return redirect(url_for('register'))
        # 先检查是否有空值
        elif not all([username, password, password2]):
            flash('请输入完整信息', 'warning')
        # 再检查用户名长度
        elif len(username) > 12 or len(username) < 3:
            flash('用户名控制在3~12位', 'user-name-error')
        # 然后检查密码长度
        elif len(password) < 6:
            flash('密码至少6位', 'password-error')
        # 最后检查密码一致性
        elif password != password2:
            flash('密码不一致', 'password2-error')
        else:
            # 存储用户信息
            users[username] = password
            session['username'] = username
            session['password'] = password
            flash('注册成功，请登录', 'success')
            return redirect(url_for('login'))
    return render_template('register.html', form_data=form_data)


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        # 验证用户信息
        if username in users and users[username] == password:
            # 将用户信息存入session
            session['username'] = username  # 存储用户名到session
            session['hasLogin'] = True  # 存储登录状态
            flash('登录成功','success')
            return redirect(url_for('index'))
        else:
            flash('用户名或密码错误','error')
            return redirect(url_for('login'))

    return render_template('login.html')


@app.route('/logout')
def logout():
    # 清除session中的用户信息
    session.pop('username', None)
    session.pop('hasLogin', None)
    flash('已退出登录')
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True,port=5001)